package com.xiyuan.smartutils.client.http.ws.impl;

import com.xiyuan.smartutils.client.http.ws.WebSocketPacket;

import java.nio.ByteBuffer;

/**
 * @author xiyuan-lgz 2024-11-03 @version v1.0.0 新建与整理
 */
public class WebSocketBufferManager {
    private boolean enableMiddleFrameEvent = false;
    private ByteBuffer fragmentBuf;
    
    /**
     * init management fragment buffer.
     */
    public void reset() {
        this.fragmentBuf = null;
    }
    
    public boolean isEnableMiddleFrameEvent() {
        return enableMiddleFrameEvent;
    }
    
    public WebSocketBufferManager setEnableMiddleFrameEvent(boolean enableMiddleFrameEvent) {
        this.enableMiddleFrameEvent = enableMiddleFrameEvent;
        return this;
    }
    
    public ByteBuffer get(ByteBuffer buffer) {
        return null;
    }
    
    
    public ByteBuffer merge(ByteBuffer buffer, WebSocketPacket.PacketHeader header) {
        if (this.enableMiddleFrameEvent) {return buffer;}
        
        
        // 处理buffer
        if (fragmentBuf != null && fragmentBuf.hasRemaining()) {
            ByteBuffer buf = ByteBuffer.allocate(fragmentBuf.remaining() + buffer.remaining());
            buf.put(fragmentBuf);
            buf.put(buffer);
            buf.flip();
            buffer = buf;
            this.fragmentBuf = buf;
        }
        if (!header.isFragmented()) this.reset();
        return buffer;
    }
}
